package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.flow.util.FlowUpdateAuditUtil;
import com.softer.wxzj.common.flow.util.Result;
import com.softer.wxzj.common.logic.GenerateAccount;
import com.softer.wxzj.common.shiro.AuthRealm;
import com.softer.wxzj.common.shiro.CredentialMatcher;
import com.softer.wxzj.common.shiro.ShiroUtil;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.entity.base.BaseEntity;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseOrganizationService;
import com.softer.wxzj.service.ZoneCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *    
 *  @ClassName: BaseOrganizationServiceImpl
 *  @Description: 企业基本信息
 *  @Author:  zcz 
 *  @CreateDate: 2019-05-10   
 */
@Service
@Slf4j
public class BaseOrganizationServiceImpl implements BaseOrganizationService {
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private BaseOrganizationMapper organizationMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private FlowUpdateAuditUtil flowUpdateAuditUtil;
    @Autowired
    private Result result;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private ModifyUtil<BaseOrganization> modifyUtil;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private ZoneCodeService zoneCodeService;
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private CombineEntityUtil<BaseOrganization> combineEntityUtil;
    @Autowired
    private DicContentMapper dicContentMapper;
    @Autowired
    private ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private BaseOwnerCommitteeMapper baseOwnerCommitteeMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private GenerateAccount generateAccount;
    @Autowired
    private SysOperatorMapper sysOperatorMapper;
    @Autowired
    private AuthRealm authRealm;
    @Autowired
    private CredentialMatcher credentialMatcher;
    @Autowired
    FlowAuditdetailMapper flowAuditdetailMapper;
    @Autowired
    private OrgRegionMapper orgRegionMapper;
    @Autowired
    private BaseModifyDetailServiceImpl baseModifyDetailService;
    @Value("${pwd}")
    private String defaultPwd;
    @Override
    public PageInfo<BaseOrganization> getAuditList(Page page, BaseOrganization organization, String flowType) {
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(flowType);
        List<BaseOrganization> list = new ArrayList<>();

        if (null != map) {
            result.select(map, organization);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = organizationMapper.getListSubmit(organization);
        }
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult addAudit(String businessId, String opinion, String mark) {
        int i = NumberEnum.ZERO.getNum();
        String auditState = flowAddAuditUtil.audit(businessId, opinion, mark,null);
        if (null != auditState) {
            i = NumberEnum.ONE.getNum();
            //不在审核中则更新业务表
            if (!FlowStateEnum.IN_AUDIT.getState().equals(auditState)) {
                BaseOrganization organization = new BaseOrganization();
                organization.setId(businessId);
                result.result(auditState, organization);
                i = organizationMapper.update(organization);
            }
//            if (auditState.equals("2")) {
//                BaseOrganization baseOrganization = organizationMapper.getInfo(businessId);
//                changeSysOper(baseOrganization);
//            }
        }
        return CommonResult.ResponseResult(i);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult modifyAudit(String id, String opinion, String mark) {
        int num = NumberEnum.ZERO.getNum();
        //查询业务id   注意区分id
        String businessId = baseModifyReqMapper.getBusinessId(id);
        if (StringUtils.isNotBlank(businessId)) {
            String auditState = flowUpdateAuditUtil.audit(businessId, opinion, mark);
            if (null != auditState) {
                num = NumberEnum.ONE.getNum();
                //终审成功，修改业务表    其他状态不做处理
                CommonResult result = dealPassModify(auditState, businessId, id);
                if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 处理变更审核通过
     *
     * @param auditState 审核结果
     * @param businessId 业务ID
     * @param id         变更Id
     * @return 处理结果
     */
    private CommonResult dealPassModify(String auditState, String businessId, String id) {
        //终审成功，修改业务表    其他状态不做处理
        if (FlowStateEnum.PASS.getState().equals(auditState)) {
            //查询数据库原数据
            BaseOrganization info = organizationMapper.getInfo(businessId);
            //变更值合并到原数据
            BaseOrganization completeEntity = modifyUtil.getCompleteEntity(id, info);
            //全表更新
            int num = organizationMapper.updateById(completeEntity);
            if (num <= NumberEnum.ZERO.getNum()) {
                return CommonResult.ResponseResult(num);
            }
            // 更新图档
            return fileService.dealPassModifyFile(id, businessId);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult submitAudit(String id,String operNo) {
        BaseOrganization base = organizationMapper.getInfo(id);
        int flowNum = base.getFlowNum() + 1;
        change(base);
        int num = NumberEnum.ZERO.getNum();
        //查询业务是否为保存状态
        if (flowNum == 1) {
            int countById = organizationMapper.getCountById(id);
            if (NumberEnum.ZERO.getNum() == countById) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该企业状态不对");
            }
        }
        //修改审批次数
        num = organizationMapper.updateFlowNum(id, flowNum);
        if (NumberEnum.ZERO.getNum() == num) {
            return CommonResult.ResponseResult(num, "修改审批次数失败");
        }
        //指定业务id和流程类型
        String initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.ORGANIZATION_ADD.getType(), StringUtils.isNotEmpty(operNo)?operNo:null);
        //判断返回值状态   当为2时更新业务表
        if (StringUtils.isNotBlank(initState)) {
            num = organizationMapper.updateFlowStateById(id, initState);
        }
//        if (initState.equals("2")) {
//            changeSysOper(base);
//        }
        return CommonResult.ResponseResult(num);
    }


    /**
     * @param baseOrganization
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult submitAuditAndAdd(BaseOrganization baseOrganization) {
        CommonResult commonResult = insert(baseOrganization);
        if (commonResult.getData() == ShiroResultEnum.SUCCESS.getCode()) {
            CommonResult commonResult1 = submitAudit(commonResult.getId(),commonResult.getOperNo());
            if (commonResult1.getData() != ShiroResultEnum.SUCCESS.getCode()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "提交数据失败");
            }
        } else {
            return commonResult;

        }
        return commonResult;
    }

    /**
     * @param baseOrganization
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateAndAdd(BaseOrganization baseOrganization) {
        String operator = sysOperatorMapper.getMainOperatorByCompanyId(baseOrganization.getId());
        CommonResult commonResult = update(baseOrganization);
        commonResult.setOperNo(operator);
        if (commonResult.getData() == ShiroResultEnum.SUCCESS.getCode()) {
            CommonResult commonResult1 = submitAudit(baseOrganization.getId(),baseOrganization.getOperNo());
            if (commonResult1.getData() != ShiroResultEnum.SUCCESS.getCode()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "提交审核失败");
            }
        } else {
            return commonResult;
        }
        return commonResult;
    }

    @Override
    public CommonResult auditPass(String id) {
        int num = organizationMapper.updateFlowStateById(id, String.valueOf(NumberEnum.TWO.getNum()));
        return CommonResult.ResponseResult(num);
    }

    public int change(BaseOrganization baseOrganization) {
        int num = 0;
        num = baseModifyDetailMapper.selectCommitteName(baseOrganization.getOrgName());
        if (num > 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "名称已被使用");
        }
        num = baseModifyDetailMapper.selectCommitteNum(baseOrganization.getOrgCertificate());
        if (num > 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "统一信用代码已被使用");
        }
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.findByNo(baseOrganization.getOrgCertificate());
        if (null != baseOwnerCommittee) {
            return 0;
        }
        int count = organizationMapper.getCountByOrgCertificate(baseOrganization.getOrgCertificate());
        if (count > 0) {
            if (count == 1) {
                BaseOrganization base = organizationMapper.getIdByNo(baseOrganization.getOrgCertificate());
                if (!base.getId().equals(baseOrganization.getId())) {
                    return 0;
                }
            } else {
                return 0;

            }
        }
        int no = organizationMapper.selectName(baseOrganization.getOrgName());
        if (no > 0) {
            if (no == 1) {
                BaseOrganization base = organizationMapper.getIdByName(baseOrganization.getOrgName());
                if (!base.getId().equals(baseOrganization.getId())) {
                    return 1;
                }
            } else {
                return 1;
            }
        }
        return 2;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult modify(BaseOrganization baseOrganization) throws Exception {
        //查询
        String modifyType = baseOrganization.getModifyType();
        String modifyCause = baseOrganization.getModifyCause();
        if (change(baseOrganization) == 0) {
            return CommonResult.ResponseResult(0, "统一信用代码已存在");
        } else if (change(baseOrganization) == 1) {
            return CommonResult.ResponseResult(0, "名称已存在");
        }
        String id = baseOrganization.getId();

        //获取原始业务数据   2审批通过：可变更
        BaseOrganization oldBaseOrganization = organizationMapper.getInfoByIdAndFlowState(id, String.valueOf(NumberEnum.TWO.getNum()));
        //赋值，避免对比后不一致（前端实体只有null不会对比）
        baseOrganization.setFlowState(oldBaseOrganization.getFlowState());
        baseOrganization.setCreateFrom(oldBaseOrganization.getCreateFrom());
        //变更类型表id    注意区分id!!
        String uuid = UUIDUtil.getUUID();
        //保存变更表
        int num = modifyUtil.updateToSave(oldBaseOrganization, baseOrganization, id, modifyType, modifyCause, uuid);
        if (NumberEnum.MINUS_ONE.getNum() == num) {
            num = 0;
        }
        // 图档变更操作
        int count = fileService.modifyFile(baseOrganization.getFileTypeList(), id, modifyType, modifyCause, uuid);
        if ((num + count) <= NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败！请检查变更数据！");
        }

        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(id, uuid, FlowTypeEnum.ORGANIZATION_MODIFY.getType(), null);
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        //终审成功，修改业务表    其他状态不做处理
        CommonResult result = dealPassModify(initState, id, uuid);
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    @Override
    public CommonResult delete(String id) {
        int count = flowInstanceMapper.getCountByBusinessId(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在审核中信息，不允许删除！");
        }
        count = baseRegionInfoMapper.selectDevelopNo(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "小区绑定该信息，不允许删除！");
        }
        count = baseRegionInfoMapper.selectPropertyNo(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "小区绑定该信息，不允许删除！");
        }
        count = baseBuildInfoMapper.selectEnvironNo(id);

        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "自然幢绑定该信息，不允许删除！");
        }
        count = baseBuildInfoMapper.selectDevelopNo(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "自然幢绑定该信息，不允许删除！");
        }
        int num = organizationMapper.delete(id);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public CommonResult updateState(String id, String state) {
        //todo 该状态时判断是否有在途业务
        int num = organizationMapper.updateStateById(id, state);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<BaseOrganization> getModifyAuditList(Page page, BaseOrganization baseOrganization) {
        //参数验证
        if (null == baseOrganization || StringUtils.isBlank(baseOrganization.getFlowState())) {
            return null;
        }
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.ORGANIZATION_MODIFY.getType());
        List<BaseOrganization> list = new ArrayList<>();
        if (null != map) {
            result.select(map, baseOrganization);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = organizationMapper.getModifyReqList(baseOrganization);

        }
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseOrganization> getModifyList(Page page, BaseOrganization baseOrganization) {
        //参数验证
        if (null == baseOrganization || StringUtils.isBlank(baseOrganization.getFlowState())) {
            return null;
        }
        //赋值区域,重要
        baseOrganization.setZoneCode(zoneCodeUtil.getZoneCode());
        //参数转换
        //setFuzzyParam(baseOrganization);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOrganization> list = organizationMapper.getModifyReqList(baseOrganization);
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseModifyDetail> getModifyDetailList(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseModifyDetail> list = organizationMapper.getModifyDetailList(id);
        //代码中文转换
        for (BaseModifyDetail modifyDetail : list) {
            switch (modifyDetail.getColumnName()) {
                case "degreeCode":
                    String oldDegreeCode = "";
                    String newDegreeCode = "";
                    if (StringUtils.isNotBlank(modifyDetail.getOldValue())) {
                        oldDegreeCode = dicContentMapper.selectName(modifyDetail.getOldValue());
                    }
                    if (StringUtils.isNotBlank(modifyDetail.getNewValue())) {
                        newDegreeCode = dicContentMapper.selectName(modifyDetail.getNewValue());
                    }

                    modifyDetail.setNewValue(null == newDegreeCode ? "" : newDegreeCode);
                    modifyDetail.setOldValue(null == oldDegreeCode ? "" : oldDegreeCode);
                    break;
                case "regionCode":
                    String newName = "";
                    String oldName = "";
                    String newRegionCode = modifyDetail.getNewValue();
                    String oldRegionCode = modifyDetail.getOldValue();
                    ZoneCode newZoneCode = zoneCodeMapper.getInfoByZoneCode(newRegionCode);
                    ZoneCode oldZoneCode = zoneCodeMapper.getInfoByZoneCode(oldRegionCode);
                    newName = zoneCodeService.zoneName(newZoneCode);
                    oldName = zoneCodeService.zoneName(oldZoneCode);
                    modifyDetail.setNewValue(newName);
                    modifyDetail.setOldValue(oldName);
                    break;
            }
            if (StringUtils.isNotBlank(modifyDetail.getCreater())) {
                String creater = sysOperatorMapper.selectAllName(modifyDetail.getCreater());
                modifyDetail.setCreater(creater);
            }

        }
        PageInfo<BaseModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult getCountByIdAndCreater(String id) {
        int count = organizationMapper.getCountByIdAndCreater(id, ShiroUserUtil.getUserName());
        if (count == 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "非创建人，不允许操作！");
        }
        return new CommonResult(ShiroResultEnum.SUCCESS.getCode(), "允许操作");
    }

    /**
     * 开发企业
     *
     * @return
     */
    @Override
    public List<BaseOrganization> selectOpenCommittee(String id) {
        return organizationMapper.selectOpenCommittee(id);
    }

    /**
     * 物业企业
     *
     * @return
     */
    @Override
    public List<BaseOrganization> selectProperty(String id) {
        return organizationMapper.selectProperty(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized CommonResult insert(BaseOrganization organization) {
        int change = change(organization);
        if (change == 0) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "统一信用代码已存在");
        } else if (change == 1) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "名称已存在");
        }
        BigInteger regNum;
        BigInteger add = new BigInteger(NumStrEnum.ONE.getNum());
        String regNo = organizationMapper.selectMaxRegeditCode(organization.getOrgTypeCode());
        if (StringUtils.isBlank(regNo)) {
            regNo = NumStrEnum.ZERO.getNum();
            regNum = new BigInteger(regNo);
            String rNo = String.format("%09d", regNum);
            setCode(organization, rNo);
        } else {
            regNum = new BigInteger(regNo);
            regNum = regNum.add(add);
            String rNo = String.format("%09d", regNum);
            organization.setRegeditCode(rNo);
        }
        String id = UUIDUtil.getUUID();
        //生成账号
        String operNo = generateAccount.generateAccount(organization.getOrgTypeCode());
        createSysOperator(organization, id, operNo);
        if (String.valueOf(NumberEnum.TWO.getNum()).equals(organization.getFlowState())) {
            organization.setRecDate(DateUtils.getNow());
            organization.setFlowNum(1);
            flowUtil.saveDefaultFlowInstance(UUIDUtil.getUUID(), id, FlowTypeEnum.ORGANIZATION_ADD.getType(), null,null);
        }
        if (StringUtils.isBlank(organization.getFlowState())) {
            organization.setFlowState("0");
        }
        organization.setId(id);
        organization.setCreater(ShiroUserUtil.getUserName());
        organization.setBuildDate(ParamUtil.setParam(organization.getBuildDate()));
        int i = organizationMapper.insert(organization);
        if (i <= NumberEnum.ZERO.getNum()) {
            throw new CourseException(NumberEnum.ZERO.getNum(), "保存失败");
        }
        //保存图片
        CommonResult commonResult = fileService.addFile(organization.getFileTypeList(), organization.getId());
        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
        }
        return CommonResult.idResult(i, id, operNo);
    }

    /**
     * 生成账号
     *
     * @param baseEntity 企业信息
     * @param id         企业ID
     * @param operNo     账号
     */
    @Override
    public void createSysOperator(BaseEntity baseEntity, String id, String operNo) {
        SysOperator sysOperator = new SysOperator();
        sysOperator.setAddType("0");
        String pwd;
        //添加类型  1企业添加   0外网注册
        if (StringUtils.isBlank(baseEntity.getPassWord())) {
            pwd = defaultPwd;
        } else {
            pwd = baseEntity.getPassWord();
        }
        sysOperator.setCreater(ShiroUserUtil.getUserName());
        sysOperator.setOperNo(operNo);
        sysOperator.setState("1");
        sysOperator.setZoneCode(baseEntity.getZoneCode());
        sysOperator.setOperName(baseEntity.getOrgName());
        sysOperator.setCompanyId(id);
        sysOperator.setCreater(ShiroUserUtil.getUserName());
        sysOperator.setCompanyNo(baseEntity.getOrgTypeCode());
        //若是注册时则他的角色是固定的
        if (StringUtils.isBlank(baseEntity.getGrade())) {
            sysOperator.setRoleCode("1" + baseEntity.getOrgTypeCode().substring(1));
            sysOperator.setGrade("1");
        } else {
            sysOperator.setRoleCode(baseEntity.getRoleCode());
            sysOperator.setGrade(baseEntity.getGrade());
        }
        //生成盐
        String salt = ShiroUtil.createSalt();
        String passWord = ShiroUtil.createPassWord(pwd, salt);
        sysOperator.setOperPwd(passWord);
        sysOperator.setSalt(salt);
        sysOperatorMapper.insert(sysOperator);
    }

    private void setCode(BaseOrganization organization, String rNo) {
        String one = "01";
        String two = "02";
        String three = "03";
        String four = "04";
        String eight = "08";
        if (one.equals(organization.getOrgTypeCode())) {
            //开发企业6开头
            organization.setRegeditCode(NumStrEnum.SIX.getNum() + rNo);
        } else if (two.equals(organization.getOrgTypeCode())) {
            //物业企业7开头
            organization.setRegeditCode(NumStrEnum.SEVEN.getNum() + rNo);
        } else if (three.equals(organization.getOrgTypeCode())) {
            //施工企业8开头
            organization.setRegeditCode(NumStrEnum.EIGHT.getNum() + rNo);
        } else if (four.equals(organization.getOrgTypeCode())) {
            //监理企业9开头
            organization.setRegeditCode(NumStrEnum.NINE.getNum() + rNo);
        } else if (eight.equals(organization.getOrgTypeCode())) {
            //审计企业0开头
            organization.setRegeditCode(NumStrEnum.ZERO.getNum() + rNo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult update(BaseOrganization organization) {
        //对前端传的多余字段附初始值（前端实体只有null不会合并到主实体）
        organization.setFlowState(null);
        if (change(organization) == 0) {
            return CommonResult.ResponseResult(0, "统一信用代码已存在");
        } else if (change(organization) == 1) {
            return CommonResult.ResponseResult(0, "名称已存在");
        }
        //查询原始数据
        BaseOrganization info = organizationMapper.getInfo(organization.getId());
        //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
        BaseOrganization baseOrganization = combineEntityUtil.combineEntity(organization, info);
        //注意是全表更新
        int num = organizationMapper.updateById(baseOrganization);
        //处理图片修改
        CommonResult result = fileService.updateFile(baseOrganization.getFileTypeList(), baseOrganization.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateSelective(BaseOrganization baseOrganization) {
        int num = organizationMapper.update(baseOrganization);
        //处理图片修改
        CommonResult result = fileService.updateFile(baseOrganization.getFileTypeList(), baseOrganization.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 查询开发企业，物业企业，施工企业，监理企业，审计企业下拉列表
     *
     * @param id   小区ID
     * @param type 类型 （01开发企业，02物业企业，03施工企业，04监理企业，08审计企业）
     * @return 企业下拉列表
     */
    @Override
    public List<BaseOrganization> getOrgList(String id, String type) {
        return organizationMapper.getOrgList(id, type);
    }

    @Override
    public PageInfo<BaseOrganization> getList(Page page, BaseOrganization baseOrganization) {
        //赋值区域,重要
        baseOrganization.setZoneCode(zoneCodeUtil.getZoneCode());
        //模糊查询赋值
        //setFuzzyParam(baseOrganization);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOrganization> list = organizationMapper.getList(baseOrganization);
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public BaseOrganization getInfo(String id) {
        return null;
    }

    @Override
    public PageInfo<BaseOrganization> getRecordList(Page page, BaseOrganization baseOrganization) {
     baseOrganization.setCreateFrom(null);
        //赋值区域,重要
        baseOrganization.setZoneCode(zoneCodeUtil.getZoneCode());
        baseOrganization.setFlowState(String.valueOf(NumberEnum.TWO.getNum()));
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOrganization> list = organizationMapper.getList(baseOrganization);
         PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseOrganization> getWaitSubmitList(Page page, BaseOrganization baseOrganization) {
        baseOrganization.setCreater(ShiroUserUtil.getUserName());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOrganization> list = organizationMapper.getList(baseOrganization);
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据id获取企业详情
     *
     * @param id 企业id
     * @param id 图档大类
     * @return 企业基本信息
     */
    @Override
    public BaseOrganization getInfoById(String id, String arcType) {
        BaseOrganization baseOrganization = organizationMapper.getInfo(id);
        String superiors;
        SysOperator user = ShiroUserUtil.getUser();
        if (NumStrEnum.ZERO.getNum().equals(user.getAddType())) {
            superiors = zoneCodeService.zoneCodeSuperiorsAll(baseOrganization.getRegionCode());
        } else {
            superiors = zoneCodeService.zoneCodeSuperiors(baseOrganization.getRegionCode(), ShiroUserUtil.getUserName());
        }
        baseOrganization.setRegionCode(superiors);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        baseOrganization.setFileTypeList(fileVOList);
        return baseOrganization;
    }

    @Override
    public CommonResult selectByPassWord(BaseOrganization base) {
        String flowState = "";
        BaseOrganization baseOrganization = organizationMapper.selectByOrgCertificate(base.getOrgCertificate());
        if (null == baseOrganization) {
            return CommonResult.ResponseResult(0, "统一信用代码不存在");
        }
        switch (baseOrganization.getFlowState()) {
            case "0":
                flowState = "保存中";
                break;
            case "1":
                flowState = "审核中";
                break;
            case "2":
                flowState = "审核通过";
                break;
            case "3":
                flowState = "审核失败";
                break;
        }
        List<SysOperator> sysOperator = sysOperatorMapper.selectByPwdAndCompany(baseOrganization.getId());
        if (null != sysOperator) {
            for (SysOperator s : sysOperator) {
                UsernamePasswordToken token = new UsernamePasswordToken(s.getOperNo(), base.getPassWord());
                authRealm.doGetAuthenticationInfo(token);
                boolean n = credentialMatcher.doCredentialsMatch(token, authRealm.doGetAuthenticationInfo(token));
                if (n == false) {
                    continue;
                } else {
                    return CommonResult.idResult(1, flowState, s.getOperNo());
                }
            }
            //AuthenticationToken authenticationToken = (AuthenticationToken) token;
        } else {
            return CommonResult.ResponseResult(0, "统一信用代码或登录密码错误");
        }
        return CommonResult.ResponseResult(0, "统一信用代码或登录密码错误");
    }

    /**
     * 重置密码
     *
     * @param baseOrganization
     * @return
     */
    @Override
    public CommonResult resetPassword(BaseOrganization baseOrganization) {
        BaseOrganization base = organizationMapper.selectByOrgCertificate(baseOrganization.getOrgCertificate());
        if (null == base) {
            return CommonResult.ResponseResult(0, "统一信用代码或账号错误");
        }
        List<SysOperator> sysOperator = sysOperatorMapper.selectByPwdAndCompany(base.getId());
        for (SysOperator s : sysOperator) {
            if (!s.getOperNo().equals(baseOrganization.getOperNo())) {
                continue;
            } else {
                String salt = ShiroUtil.createSalt();
                String passWord = ShiroUtil.createPassWord(baseOrganization.getPassWord(), salt);
                s.setOperPwd(passWord);
                s.setSalt(salt);
                int num = sysOperatorMapper.update(s);
                if (num > 0) {
                    return CommonResult.ResponseResult(num, "密码重置成功，请妥善保存新密码");
                }
            }
        }
        return CommonResult.ResponseResult(0, "统一信用代码或账号错误");

    }

    @Override
    public BaseOrganization rejectionExaminationApproval(String operNo, String arcType) {
        BaseOrganization baseOrganization = getOrg(operNo);
        String superiors = zoneCodeService.zoneCodeSuperiorsAll(baseOrganization.getRegionCode());
        baseOrganization.setRegionCode(superiors);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(baseOrganization.getId(), arcType);
        baseOrganization.setFileTypeList(fileVOList);
        //审核意见
        String opinion = flowAuditdetailMapper.getOpinion(baseOrganization.getId(), FlowTypeEnum.ORGANIZATION_ADD.getType());
        //是不是在变更
        BaseModifyReq baseModifyReq = baseModifyReqMapper.selectFlowStateById(baseOrganization.getId(), "organization_modify");
        if (null != baseModifyReq) {
            baseOrganization.setUpdateFlowState(baseModifyReq.getFlowState());
        }
        baseOrganization.setOpinion(opinion);
        return baseOrganization;
    }

    /**
     * 根据登录账号，查询企业信息
     *
     * @param operNo 登录账号
     * @return 企业信息
     */
    public BaseOrganization getOrg(String operNo) {
        SysOperator sysOperator = sysOperatorMapper.selectName(operNo);
        return organizationMapper.getInfo(sysOperator.getCompanyId());
    }

    /**
     * 获取外网确认变更接口
     *
     * @param modifyVO 变更项集合
     * @return 变更结果
     */
    @Override
    public CommonResult getExtraNetModify(ModifyVO modifyVO) {
        String uuid = UUIDUtil.getUUID();
        SysOperator sysOperator = sysOperatorMapper.selectName(modifyVO.getOperNo());
        String companyId = sysOperator.getCompanyId();
        //新增一条变更记录
        int num = modifyUtil.saveModifyReq(uuid, companyId, FlowTypeEnum.ORGANIZATION_MODIFY.getType(), modifyVO.getModifyCause(), modifyVO.getOperNo());
        if (num == 0) {
            return CommonResult.ResponseResult(num, "新增变更记录失败");
        }
        //新增变更详情
        List<BaseModifyDetail> list = modifyVO.getList();
        dealList(list, uuid, sysOperator.getOperName());
        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(companyId, uuid, FlowTypeEnum.ORGANIZATION_MODIFY.getType(), modifyVO.getOperNo());
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        //终审成功，修改业务表    其他状态不做处理
        CommonResult result = dealPassModify(initState, companyId, uuid);
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(1);
    }

    public void dealList(List<BaseModifyDetail> list, String uuid, String operatorName) {
        for (int i = 0; i < list.size(); i++) {
            BaseModifyDetail baseModifyDetail = list.get(i);
            int count = modifyUtil.saveModifyDetail(baseModifyDetail, uuid);
            if (count != 1) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
            }
            String type = baseModifyDetail.getType();
            if (NumStrEnum.THREE.getNum().equals(type)) {
                // 图档的变更项，加入base_modify_file_detail
                List<String> oldPathList = baseModifyDetail.getOldPathList();
                List<String> newPathList = baseModifyDetail.getNewPathList();
                int fileNum = fileService.addFileDetailPath(oldPathList, newPathList, baseModifyDetail.getFileType(), baseModifyDetail.getId(), operatorName);
                if (fileNum == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "图档变更失败，请重新操作");
                }
            }
        }
    }

    /**
     * 查询监理企业信息
     * (用于外网调用，只查询监理人和监理电话)
     *
     * @param id 监理企业ID
     * @return 监理企业信息
     */
    @Override
    public BaseOrganization getOrgSupervisionInfo(String id) {
        return organizationMapper.getOrgSupervisionInfo(id);
    }

    /**
     * 获取外网提醒列表
     *
     * @param page   分页实体
     * @param operNo 登录账号
     * @return 提醒列表
     */
    @Override
    public PageInfo<MessageVO> getReminder(Page page, String operNo) {
        //查询提醒列表
        SysOperator operator = sysOperatorMapper.getOperInfoByOperNo(operNo);
        //查询登录账号下管理的小区
        String regionIdList = orgRegionMapper.getRegionIdList(operNo);
        //查询单位信息变更申请列表
        List<MessageVO> orgModifyList = getOrgModifyList(operator.getCompanyId());
        //查询区域绑定列表
        List<MessageVO> orgRegionList = getOrgRegionList(operNo);
        //查询项目申请列表
        List<MessageVO> expList = getExpList(regionIdList, operator.getCompanyId());
        //查询拨款申请列表
        List<MessageVO> expPayList = getExpPayList(regionIdList, operator.getCompanyId());
        //查询拨款申请撤销列表
        List<MessageVO> expPayRevocationList = getExpPayRevocationList(regionIdList, operator.getCompanyId());
        //查询收款账户变更列表
        List<MessageVO> orgBankModifyList = getOrgBankModifyList(operator.getCompanyId());
        //查询收款账户资金到账列表
        List<MessageVO> accKeepList = getAccKeepList(regionIdList, operator.getCompanyId());
        List<MessageVO> resultList = new ArrayList<>();
        resultList.addAll(orgModifyList != null ? orgModifyList : new ArrayList<>());
        resultList.addAll(orgRegionList != null ? orgRegionList : new ArrayList<>());
        resultList.addAll(expList != null ? expList : new ArrayList<>());
        resultList.addAll(expPayList != null ? expPayList : new ArrayList<>());
        resultList.addAll(expPayRevocationList != null ? expPayRevocationList : new ArrayList<>());
        resultList.addAll(orgBankModifyList != null ? orgBankModifyList : new ArrayList<>());
        resultList.addAll(accKeepList != null ? accKeepList : new ArrayList<>());

        PageInfo<MessageVO> pageInfo = new PageInfo<>();
        if (resultList.size() > 0) {
            List<MessageVO> b = baseModifyDetailService.pageAll(page, resultList);
            pageInfo = new PageInfo<>(b);
            pageInfo.setTotal(resultList.size());
        }
        return pageInfo;
    }

    /**
     * 查询收款账户资金到账列表
     *
     * @param regionIdList 管理的小区ID（以逗号分隔）
     * @param companyId    申请企业ID
     * @return 收款账户资金到账列表
     */
    private List<MessageVO> getAccKeepList(String regionIdList, String companyId) {
        return organizationMapper.getAccKeepList(regionIdList, companyId);
    }

    /**
     * 查询收款账户变更列表
     *
     * @param companyId 企业ID
     * @return 收款账户变更列表
     */
    private List<MessageVO> getOrgBankModifyList(String companyId) {
        return organizationMapper.getOrgBankModifyList(companyId);
    }

    /**
     * 查询单位信息变更申请列表
     *
     * @param companyId 企业ID
     * @return 单位信息变更申请列表
     */
    private List<MessageVO> getOrgModifyList(String companyId) {
        return organizationMapper.getOrgModifyList(companyId);
    }

    /**
     * 查询区域绑定列表
     *
     * @param operNo 登录账号
     * @return 区域绑定列表
     */
    private List<MessageVO> getOrgRegionList(String operNo) {
        return organizationMapper.getOrgRegionList(operNo);
    }

    /**
     * 查询拨款申请撤销列表
     *
     * @param regionIdList 管理的小区ID（以逗号分隔）
     * @param companyId    申请企业ID
     * @return 拨款申请撤销列表
     */
    private List<MessageVO> getExpPayRevocationList(String regionIdList, String companyId) {
        return organizationMapper.getExpPayRevocationList(regionIdList, companyId);
    }

    /**
     * 查询拨款申请列表
     *
     * @param regionIdList 管理的小区ID（以逗号分隔）
     * @param companyId    申请企业ID
     * @return 拨款申请列表
     */
    private List<MessageVO> getExpPayList(String regionIdList, String companyId) {
        return organizationMapper.getExpPayList(regionIdList, companyId);
    }

    /**
     * 查询项目申请列表
     *
 * @param regionIdList 管理的小区ID（以逗号分隔）1  去·  568=-8  -0i【】、】【dfyuop8f ;ueqwt6=.,`    `   234\
     *
     * @param companyId    申请企业ID
     * @return 项目申请列表
     */
    private List<MessageVO> getExpList(String regionIdList, String companyId) {
        return organizationMapper.getExpList(regionIdList, companyId);
    }

    /**
     * 外网获取变更信息列表
     *
     * @param page         分页信息
     * @param organization 查询信息
     * @return 企业变更列表
     */
    @Override
    public PageInfo<BaseOrganization> getModifyListToExtraNet(Page page, BaseOrganization organization) {
        BaseOrganization org = getOrg(organization.getOperNo());
        organization.setId(org.getId());
        organization.setModifyType(FlowTypeEnum.ORGANIZATION_MODIFY.getType());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOrganization> list = organizationMapper.getModifyListToExtraNet(organization);
        PageInfo<BaseOrganization> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 施工企业
     *
     * @return
     */
    @Override
    public List<BaseOrganization> getSGOrgInfo() {
        return organizationMapper.selectSGOrgIdName();
    }

    /**
     * 审计企业
     *
     * @return
     */
    @Override
    public List<BaseOrganization> getSJOrgInfo() {
        return organizationMapper.selectSJOrgIdName();
    }

    /**
     * 监理企业
     *
     * @return
     */
    @Override
    public List<BaseOrganization> getJLOrgInfo() {
        return organizationMapper.selectJLOrgIdName();
    }

    /**
     * 查询小区下的申请单位信息
     *
     * @param id 小区id
     * @return
     */
    @Override
    public List<BaseOrganization> getSQOrgInfo(String id) {
        List<BaseOrganization> bo = organizationMapper.selectOrgByRegionId(id);
        List<BaseOrganization> bo2 = organizationMapper.selectOrgByRegionId2(id);
        bo.addAll(bo2);
        return bo;
    }

    @Override
    public CommonResult selectName(String name) {
        int num = organizationMapper.selectName(name);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<BaseRegionInfo> selectCountByDev(Page page, BaseRegionInfo baseRegionInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> base = baseRegionInfoMapper.selectCountByDev(baseRegionInfo);
        if (base.isEmpty()) {
            return null;
        }
        if (base.size() == 1 && StringUtils.isBlank(base.get(0).getZoneCode())) {
            return null;
        }
        for (BaseRegionInfo b : base) {
            if (StringUtils.isNotBlank(b.getZoneCode())) {
                ZoneCode zoneCode = zoneCodeMapper.getInfoByZoneCode(b.getZoneCode());
                b.setZoneCodeName(zoneCodeService.zoneName(zoneCode));
            }
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(base);
        return pageInfo;
    }
}
